package com.fary.chapter03_ext_callable;

import lombok.SneakyThrows;

import java.util.concurrent.locks.LockSupport;

public class FaryFutureTask<V> implements Runnable {
    private final FaryCallable<V> faryCallable;
    private Thread cuThread;
    private V result;

    public FaryFutureTask(FaryCallable<V> faryCallable) {
        this.faryCallable = faryCallable;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 获取到faryCallable 执行返回结果
        result = faryCallable.call();
        // 如果 call方法执行完毕 则唤醒当前阻塞的线程
        if (cuThread != null)
            LockSupport.unpark(cuThread);
    }

    /**
     * 调用get方法 当前线程就会阻塞。
     */
    public V get() {
        cuThread = Thread.currentThread();
        // 阻塞当前线程
        LockSupport.park();
        return result;
    }
}